import { updateAddressAPI } from '@/services/address'
import type { AddressInfo } from '@/types/address'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const userAddressStore = defineStore(
  'address',
  () => {
    //定义选择的收货地址信息
    const selectAddress = ref<AddressInfo>()

    const changeSelectAddress = (val: AddressInfo) => {
      //持久化保存在store中
      val.fullLocation = val.provinceCode + val.cityCode + val.countyCode + val.address
      selectAddress.value = val
      // if (val.isDefault != 1) {
      //   //调用修改地址接口，修改默认值
      //   val.isDefault = 1
      //   updateAddressAPI(val, val.id)
      // }
    }

    const removeSelectAddress = () => {
      selectAddress.value = undefined
    }

    return {
      selectAddress,
      changeSelectAddress,
      removeSelectAddress,
    }
  }, // TODO: 持久化
  {
    //只能再网页端配置
    // persist: true,

    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key: string, value: any) {
          uni.setStorageSync(key, value) // [!code warning]
        },
        getItem(key: string) {
          return uni.getStorageSync(key) // [!code warning]
        },
      },
    },
  },
)
